const app = getApp()
const {
  Base
} = require('../../utils/base.js')
import {
  Config
} from '../../utils/config.js';
const {
  MemberModel
} = require('../../utils/member-model.js')
const memberModel = new MemberModel()
const http = new Base()
Component({
  data: {
    goUser: false
  },
  properties: {
    coupons: {
      type: Array,
      value: []
    },
    giftNeedLogin: {
      type: String,
      value: ''
    },
    encryptedData: {
      type: String,
      value: ''
    },
    iv: {
      type: String,
      value: ''
    }
  },
  // observers: {
  //   'giftNeedLogin': function(val) {
  //   }
  // },
  methods: {
    getPhoneNumber({
      detail
    }) {
      this.setData({
        phoneShow: false
      })
      const {
        encryptedData,
        iv
      } = detail
      if (encryptedData) {
        wx.login({
          success: ({
            code
          }) => {
            this.register(encryptedData, iv, code)
          }
        })
      }
    },
    register(encryptedData, iv, code) {
      const shareData = wx.getStorageSync('shareData') || {}
      let params = {
        sourcePartnerSign: app.globalData.sourcePartnerSign,
        shareFlag: !!app.globalData.isShare,
        code: code,
        encryptedDataUser: this.data.encryptedData,
        ivUser: this.data.iv,
        encryptedDataPhone: encryptedData,
        ivPhone: iv,
        appId: Config.appId,
        shareChannel: shareData.shareChannel,
        source: shareData.source,
        operatorId: shareData.operatorId,
        shopId: shareData.shopId
      }
      http.request({
        url: '/wechat/applet/user/register',
        data: params,
        sCallback: ({
          data,
          error,
          status
        }) => {
          if (status === 200) {
            wx.setStorageSync('token', data.token)
            app.globalData.isLogin = true
            if (data.register) {
              this.registerGift()
            }
          } else {
            wx.showToast({
              title: `${error}`,
              icon: 'none'
            })
          }
        },
        eCallback: () => {
          wx.showToast({
            icon: 'none',
            title: '会员注册失败'
          })
        }
      })
    },
    registerGift() {
      memberModel.registerGift({
        partnerSign: app.globalData.sourcePartnerSign,
        merchantId: wx.getStorageSync('merchantId')
      }).then(() => {
        this.setData({
          giftNeedLogin: '',
          goUser: true
        })
      }).catch(() => {
        wx.showToast({
          title: '领取失败',
          icon: 'none',
          duration: 2000
        })
      })
    },
    close () {
      this.triggerEvent('close')
    },
    goBeginner () {
      wx.navigateTo({
        url: '/pages/beginner/index'
      })
    }
  }
})
